package com.eduagent.xwqeduagent.api.OneSentenceReprint.api;

import com.google.gson.Gson;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 训练任务服务
 */
@Service
public class TrainTaskService {

    @Value("${xfyun.appid}")
    private String APPID;

    @Value("${xfyun.apikey}")
    private String APIKEY;

    @Autowired
    private AuthService authService;

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final Gson GSON = new Gson();
    private static final String CREATE_TASK_URL = "http://opentrain.xfyousheng.com/voice_train/task/add";
    private static final String SUBMIT_TASK_URL = "http://opentrain.xfyousheng.com/voice_train/task/submit";
    private static final String TASK_RESULT_URL = "http://opentrain.xfyousheng.com/voice_train/task/result";

    /**
     * 创建训练任务
     * @param token 鉴权token
     * @param request 创建任务请求
     * @return 创建任务响应
     * @throws Exception 请求异常时抛出
     */
    public CreateTaskResponse createTask(String token, CreateTaskRequest request) throws Exception {
        // 创建请求体
        Map<String, Object> requestJson = new HashMap<>();
        
        // 必填参数
        requestJson.put("resourceType", request.getResourceType());
        
        // 可选参数，只在非空时添加
        if (request.getTaskName() != null && !request.getTaskName().isEmpty()) {
            requestJson.put("taskName", request.getTaskName());
        }
        
        if (request.getSex() != null) {
            requestJson.put("sex", request.getSex());
        }
        
        if (request.getAgeGroup() != null) {
            requestJson.put("ageGroup", request.getAgeGroup());
        }
        
        if (request.getThirdUser() != null && !request.getThirdUser().isEmpty()) {
            requestJson.put("thirdUser", request.getThirdUser());
        }
        
        if (request.getLanguage() != null && !request.getLanguage().isEmpty()) {
            requestJson.put("language", request.getLanguage());
        }
        
        if (request.getDenoiseSwitch() != null) {
            requestJson.put("denoiseSwitch", request.getDenoiseSwitch());
        }
        
        if (request.getMosRatio() != null) {
            requestJson.put("mosRatio", request.getMosRatio());
        }
        
        if (request.getResourceName() != null && !request.getResourceName().isEmpty()) {
            requestJson.put("resourceName", request.getResourceName());
        }
        
        if (request.getCallbackUrl() != null && !request.getCallbackUrl().isEmpty()) {
            requestJson.put("callbackUrl", request.getCallbackUrl());
        }
        
        String body = GSON.toJson(requestJson);
        
        // 设置请求类型和请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody httpBody = RequestBody.create(JSON, body);

        // 生成签名
        String time = String.valueOf(System.currentTimeMillis());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(APIKEY);
        stringBuilder.append(time);
        stringBuilder.append(AuthService.to32LowerCase(body.getBytes()));
        String signature = AuthService.to32LowerCase(stringBuilder.toString().getBytes());
        
        // 构建请求
        Request httpRequest = new Request.Builder()
                .url(CREATE_TASK_URL)
                .method("POST", httpBody)
                .addHeader("X-Sign", signature)
                .addHeader("X-Token", token)
                .addHeader("X-AppId", APPID)
                .addHeader("X-Time", time)
                .build();
        
        // 发送请求并获取响应
        Response response = HTTP_CLIENT.newCall(httpRequest).execute();
        CreateTaskResponse taskResponse = GSON.fromJson(response.body().string(), CreateTaskResponse.class);
        
        // 检查响应状态
        if (taskResponse.getCode() != 0) {
            throw new RuntimeException("创建训练任务失败: " + taskResponse.getDesc());
        }
        
        return taskResponse;
    }
    
    /**
     * 提交训练任务
     * @param token 鉴权token
     * @param taskId 训练任务ID
     * @return 提交训练任务响应
     * @throws Exception 请求异常时抛出
     */
    public SubmitTaskResponse submitTask(String token, String taskId) throws Exception {
        // 验证必填参数
        if (taskId == null || taskId.isEmpty()) {
            throw new IllegalArgumentException("训练任务ID不能为空");
        }
        
        // 创建请求体
        Map<String, Object> requestJson = new HashMap<>();
        requestJson.put("taskId", taskId);
        String body = GSON.toJson(requestJson);
        
        // 设置请求类型和请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody httpBody = RequestBody.create(JSON, body);

        // 生成签名
        String time = String.valueOf(System.currentTimeMillis());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(APIKEY);
        stringBuilder.append(time);
        stringBuilder.append(AuthService.to32LowerCase(body.getBytes()));
        String signature = AuthService.to32LowerCase(stringBuilder.toString().getBytes());
        
        // 构建请求
        Request httpRequest = new Request.Builder()
                .url(SUBMIT_TASK_URL)
                .method("POST", httpBody)
                .addHeader("X-Sign", signature)
                .addHeader("X-Token", token)
                .addHeader("X-AppId", APPID)
                .addHeader("X-Time", time)
                .build();
        
        // 发送请求并获取响应
        Response response = HTTP_CLIENT.newCall(httpRequest).execute();
        SubmitTaskResponse submitResponse = GSON.fromJson(response.body().string(), SubmitTaskResponse.class);
        
        // 检查响应状态
        if (submitResponse.getCode() != 0) {
            throw new RuntimeException("提交训练任务失败: " + submitResponse.getDesc());
        }
        
        return submitResponse;
    }

    /**
     * 查询训练任务状态
     * @param token 鉴权token
     * @param taskId 训练任务ID
     * @return 训练任务状态响应
     * @throws Exception 请求异常时抛出
     */
    public TaskResultResponse getTaskResult(String token, String taskId) throws Exception {
        // 验证必填参数
        if (taskId == null || taskId.isEmpty()) {
            throw new IllegalArgumentException("训练任务ID不能为空");
        }
        
        // 创建请求体
        Map<String, Object> requestJson = new HashMap<>();
        requestJson.put("taskId", taskId);
        String body = GSON.toJson(requestJson);
        
        // 设置请求类型和请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody httpBody = RequestBody.create(JSON, body);

        // 生成签名
        String time = String.valueOf(System.currentTimeMillis());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(APIKEY);
        stringBuilder.append(time);
        stringBuilder.append(AuthService.to32LowerCase(body.getBytes()));
        String signature = AuthService.to32LowerCase(stringBuilder.toString().getBytes());
        
        // 构建请求
        Request httpRequest = new Request.Builder()
                .url(TASK_RESULT_URL)
                .method("POST", httpBody)
                .addHeader("X-Sign", signature)
                .addHeader("X-Token", token)
                .addHeader("X-AppId", APPID)
                .addHeader("X-Time", time)
                .build();
        
        // 发送请求并获取响应
        Response response = HTTP_CLIENT.newCall(httpRequest).execute();
        TaskResultResponse resultResponse = GSON.fromJson(response.body().string(), TaskResultResponse.class);
        
        return resultResponse;
    }

    /**
     * 创建训练任务请求类
     */
    @Data
    public static class CreateTaskRequest {
        private String taskName;       // 创建任务名称, 默认""
        private Integer sex;           // 性别, 1:男2:女, 默认1
        private Integer ageGroup;      // 1:儿童、2:青年、3:中年、4:中老年, 默认1
        private Integer resourceType;  // 12:一句话合成（必填）
        private String thirdUser;      // 用户标识, 默认""
        private String language;       // 训练的语种, 默认""
        private Integer denoiseSwitch; // 降噪开关, 默认0
        private Float mosRatio;        // 范围0.0～5.0，单位0.1，默认0.0
        private String resourceName;   // 音库名称, 默认""
        private String callbackUrl;    // 任务结果回调地址
    }

    /**
     * 创建训练任务响应类
     */
    @Data
    public static class CreateTaskResponse {
        private String flag;
        private int code;
        private String desc;
        private String data;  // 任务id
    }
    
    /**
     * 提交训练任务响应类
     */
    @Data
    public static class SubmitTaskResponse {
        private String flag;
        private int code;
        private String desc;
        private Object data;  // 通常为null
    }
    
    /**
     * 查询训练任务状态响应类
     */
    @Data
    public static class TaskResultResponse {
        private String flag;
        private int code;
        private String desc;
        private TaskResultData data;
        
        @Data
        public static class TaskResultData {
            private String taskName;       // 任务名称
            private String resourceName;   // 音库名称
            private int sex;               // 音库性别
            private int ageGroup;          // 音库年龄段
            private String trainVid;       // 音库id
            private String assetId;        // 训练得到的音色id，后续根据该音色id进行音频合成
            private String trainId;        // 任务唯一id
            private String appId;          // 应用id
            private int trainStatus;       // -1训练中，1成功，0失败，2草稿
            private String failedDesc;     // 训练失败原因
        }
    }
} 